<?php


namespace app\controller;

use think\facade\Db;
use think\facade\View;
use think\facade\Request;


class Wechat
{
    public function index()
    {
        $token = signToken('12312312312312');
        dump($token);
        return "Wechat index";
    }

    public function getUserInfoByToken()
    {
        $req = Request();
        $openid = $req->openid;
        $wxUser = Db::table('Sys_WeChatInf')->where('wx_h5_openid', $openid)->find();

        if(!$wxUser){
            $res = [
                "code" => -1,
                "msg" => "无此用户",
                "data" => null
            ];
        }
      
        if($wxUser['Account']){
            $AccountInfo =  Db::table("JL_CZKeHuJL")->where("Account",$wxUser['Account'])->find();
            $wxUser['AccountInfo'] = $AccountInfo;
        }
        
        $res = [
            "code" => 1,
            "msg" => "ok",
            "data" => $wxUser
        ];
        return json($res);
    }

    /**
     * 授权页面 成功后 携带 code 跳转H5
     * @return string
     */
    public function wxlogin()
    {

        return View::fetch();
    }

    /**
     * 通过 用户 授权code 注册用户
     */
    public function wxRigistByCode()
    {
        // 接收授权code码
        $code = Request::post("code");
        // 获取用户信息
        $url =
            "https://api.weixin.qq.com/sns/oauth2/access_token" .
            "?appid=" . env('WECHAT_H5APPID') .
            "&secret=" . env('WECHAT_H5SECRET') .
            "&code=" . $code .
            "&grant_type=authorization_code";
        // 查询数据库，注册/返回 用户token
        $output = httpGet($url);
        if (in_array("errcode", $output) && in_array("errmsg", $output)) {
            return json($output);
        } else {
            // dump($output);
            // 查询 此用户
            $wxUser = Db::table('Sys_WeChatInf')->where('wx_h5_openid', $output['openid'])->find();
            if ($wxUser) {
                if($wxUser['Account']){
                    $AccountInfo =  Db::table("JL_CZKeHuJL")->where("Account",$wxUser['Account'])->find();
                    $wxUser['AccountInfo'] = $AccountInfo;
                }
                $res = [
                    "code" => 1,
                    "msg" => "ok",
                    "openid" => $output['openid'],
                    // "token" => signToken($output['openid']),
                    "data" => $wxUser
                ];
                return json($res);

            } else {
                // 拉取用户头像昵称

                $getUserInfoUrl =
                    "https://api.weixin.qq.com/sns/userinfo" .
                    "?access_token=" . $output['access_token'] .
                    "&openid=" . $output['openid'] .
                    "&lang=zh_CN";
                $userInfo = httpGet($getUserInfoUrl);
                // dump($userInfo);
                $data = [
                    'wx_h5_openid' => $userInfo['openid'],
                    'nickname' => $userInfo['nickname'],
                    'sex' => $userInfo['sex'],
                    'city' => $userInfo['city'],
                    'province' => $userInfo['province'],
                    'country' => $userInfo['country'],
                    'headimgurl' => $userInfo['headimgurl'],
                    'access_token' => $output['access_token'],
                    'typecode' => '2',
                    'typename' => '散户'
                ];
                //
                $userId = Db::table('Sys_WeChatInf')->insertGetId($data);
                $userData = Db::table('Sys_WeChatInf')->find($userId);
                $openid = $userInfo['openid'];
                
                $res = [
                    "code" => 1,
                    "msg" => "ok",
                    "openid" => $openid,
                    "data" => $userData
                ];
                return json($res);
            }
        }

    }

    /**
     * 绑定用户OA 账号
     */
    public function bindAccount()
    {
        $req = Request();
        $username = $req->post("username");
        $password = $req->post("password");
        $userType = $req->post("userType");

        // 客户 
        if ($userType === '1') {
            $user = Db::table('JL_CZKeHuJL')
                ->where('Account', $req->post("username"))
                ->where('Psd', $req->post("password"))
                ->find();

            if ($user) {
                // 绑定
                $res = Db::table('Sys_WeChatInf')->where('wx_h5_openid', $req->openid)->find();
                Db::table('Sys_WeChatInf')->save([
                    'Account' => $username, 
                    'ID' => $res['ID'],
                    'typecode' => $userType,
                    'typename' => '客户',
                    'Name' => $user['Name']
                ]);
                $res["Account"] = $username;
                return json([
                    "code" => 1,
                    "msg" => "ok",
                    "data" => $res
                ]);
            } else {
                return json([
                    "code" => -1,
                    "msg" => "用户名密码错误或不存在"
                ]);
            }

        }else
        // 内部用户
        {
            
            $account = Db::table('Sys_WeChatInf')->where('Account', $req->post("username"))->find();
            if ($account) {
                return json([
                    "code" => -1,
                    "msg" => "该账号已被绑定"
                ]);
            }
            $url = "http://127.0.0.1:9001/CheckUser/?UserAccount=$username&UserPsd=$password";
            $httpRes = httpGet($url);

            if ($httpRes["code"] == 1) {

                $res = Db::table('Sys_WeChatInf')->where('wx_h5_openid', $req->openid)->find();
                Db::table('Sys_WeChatInf')->save([
                    'Account' => $username, 
                    'ID' => $res['ID'],
                    'typecode' => $userType,
                    'typename' => '内部用户'
                ]);
                $res["Account"] = $username;
                return json([
                    "code" => 1,
                    "msg" => "ok",
                    "data" => $res
                ]);
            } else {
                if (!$httpRes) {
                    return json([
                        "code" => -1,
                        "msg" => "CheckUser 服务异常"
                    ]);
                }
                return json($httpRes);
            }
        }

        


    }

    // 解绑
    public function unBindAccount()
    {
        $req = Request();
        $res = Db::table('Sys_WeChatInf')->where('wx_h5_openid', $req->openid)->find();
        Db::table('Sys_WeChatInf')->save(['Account' => null, 'ID' => $res['ID']]);
        return json([
            "code" => 1,
            "msg" => "ok"
        ]);
    }

    // 发送模板消息
    public function sendMsg()
    {


        $access_token = getWxAccessToken();
        $req = Request();

        if (!$req->isPost()) {
            return json([
                "code" => -1,
                "msg" => "不支持的请求方式"
            ]);
        }

        $openid = $req->post("openid");
        $account = $req->post("account");
        $templateid = $req->post("templateid");
        $content = $req->post("content");


        if (!($openid || $account)) {
            return json([
                "code" => -1,
                "msg" => "openid 或 account 必须传一个"
            ]);
        }
        if (!$templateid) {
            return json([
                "code" => -1,
                "msg" => "templateid 不能为空"
            ]);
        }
        if (!$content) {
            return json([
                "code" => -1,
                "msg" => "content 不能为空,且为JSON 格式"
            ]);
        }
        if (!$openid) {
            // 通过account 查询openid
            $user = Db::table('Sys_WeChatInf')->where('Account', $account)->find();
            if (!$user) {
                return json([
                    "code" => -1,
                    "msg" => "未找到此用户，请核实后再试"
                ]);
            }
            $openid = $user["wx_h5_openid"];
        }


        $data = [
            "touser" => $openid,//接收者openid
            "template_id" => $templateid,//模板ID
            "url" => "http://zsoa.gek6.com/h5/",
            "data" => json_decode($content, true)
        ];
        $postRes = httpPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$access_token", $data);
        return json([
            "code" => 1,
            "msg" => "ok",
            "data" => $postRes
        ]);

    }

    // 获取公众号JSSDK初始化签名
    public function wxh5JssdkSign()
    {

        $data = [];
        $data['share_url'] = input('share_url', '');
        if (!$data['share_url']) {
            return json([
                "code" => -1,
                "msg" => "share_url 不能为空"
            ]);
        }

        $ticket = getWxh5Ticket();

        $appid = env('WECHAT_H5APPID');
        $data['appid'] = $appid;
        
        $data['jsapi_ticket'] = $ticket;
        $data['timestamp'] = time();
        $data['noncestr'] = randomStr(16);

        //获取签名
        $signature = 'jsapi_ticket=' . $data['jsapi_ticket'] . '&noncestr=' . $data['noncestr'] . '&timestamp=' . $data['timestamp'] . '&url=' . $data['share_url'];
        $data['signature'] = sha1($signature);
        return json(
            [
                "code" => 1,
                "msg" => "ok",
                "data" => $data
            ]
        );

    }

    // 获取打卡地址范围 时间规则
    public function getSignPosition()
    {

        $time = Db::table("Sys_KaoQinDateSet")->where(["Date" => date("Y-m-d", time())])->find();
        $positions = Db::table("Sys_KaoQinPosition")->select()->toArray();
        // dump($position);
        // die();
        return json([
            "code" => 1,
            "msg" => "ok",
            "data" => [
                "time" => $time,
                "position" => $positions
            ]
        ]);
    }

    // 查询当天的打卡记录
    public function getTodaySignLog()
    {
        $req = Request();
        // 根据 openid 查询 account
        $wxUser = Db::table("Sys_WeChatInf")->where([
            "wx_h5_openid" => $req->openid
        ])->find();
        if ($wxUser) {
            $logs = Db::table("Sys_KaoQinJiLu_log")->where([
                "signDate" => date("Y-m-d", time()),
                "Account" => $wxUser['Account']
            ])->select()->toArray();
            return json([
                "code" => 1,
                "msg" => "ok",
                "data" => $logs
            ]);
        } else {
            return json([
                "code" => -1,
                "msg" => "无此用户"
            ]);
        }

    }

    // 签到
    public function sign()
    {
        $req = Request();
        $lng = $req->post()['longitude'];
        $lat = $req->post()['latitude'];
        $user = Db::table('Sys_WeChatInf')->where('wx_h5_openid', $req->openid)->find();
        $data = [];

        $logs = Db::table("Sys_KaoQinJiLu_log")->where([
            "signDate" => date("Y-m-d", time()),
            "Account" => $user['Account']
        ])->select()->toArray();
        $length = count($logs);
        // dump($logs);
        // dump("考勤记录 $length 条");

        $data['Account'] = $user['Account'];


        $data['lng'] = $lng;
        $data['lat'] = $lat;

        if ($length === 0) {
            // 创建记录
            $data['StartTime'] = time();
            $signID = Db::table("Sys_KaoQinJiLu")->strict(false)->insertGetId($data);;
            $data['kaoqinjilu_id'] = $signID;
        }

        if ($length >= 1) {
            // 已经签到第一次
            $kaoqinjilu_id = $logs[0]['kaoqinjilu_id'];
            // dump($kaoqinjilu_id);
            // 更新对应记录

            Db::table('Sys_KaoQinJiLu')
                ->where('ID', $kaoqinjilu_id)
                ->data(['EndTime' => time()])
                ->update();
            $data['kaoqinjilu_id'] = $kaoqinjilu_id;
        }

        $data['signTime'] = time();
        $data['signDate'] = date("Y-m-d", time());

        Db::table("Sys_KaoQinJiLu_log")->strict(false)->insert($data);

        return json([
            "code" => 1,
            "msg" => "ok"
        ]);
    }

    // 经纬度转地理位置
    public function position2address()
    {
        $req = Request();

        $KEY = "BU2BZ-ACDWX-B564D-ZOV3I-3CDLK-D4BZT";
        $lat = $req->get("lat");
        $lng = $req->get("lng");
        $URL = "https://apis.map.qq.com/ws/geocoder/v1/?key=$KEY&location=$lat,$lng";
        $output = httpGet($URL);
        $address = $output["result"]["formatted_addresses"]["recommend"];
        return json([
            "code" => 1,
            "msg" => "ok",
            "data" => $address
        ]);
    }
}